package com.delio.client.series;

import java.util.ArrayList;
import java.util.List;

import com.delio.client.produccion.tipodocumentos.TipoDocumentos;
import com.extjs.gxt.ui.client.Style.LayoutRegion;
import com.extjs.gxt.ui.client.binding.FieldBinding;
import com.extjs.gxt.ui.client.binding.FormBinding;
import com.extjs.gxt.ui.client.data.BeanModel;
import com.extjs.gxt.ui.client.event.ButtonEvent;
import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.GridEvent;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.event.SelectionChangedEvent;
import com.extjs.gxt.ui.client.event.SelectionChangedListener;
import com.extjs.gxt.ui.client.event.SelectionListener;
import com.extjs.gxt.ui.client.util.IconHelper;
import com.extjs.gxt.ui.client.widget.ContentPanel;
import com.extjs.gxt.ui.client.widget.Dialog;
import com.extjs.gxt.ui.client.widget.LayoutContainer;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.button.ButtonBar;
import com.extjs.gxt.ui.client.widget.form.ComboBox;
import com.extjs.gxt.ui.client.widget.form.FormPanel;
import com.extjs.gxt.ui.client.widget.form.HiddenField;
import com.extjs.gxt.ui.client.widget.form.TextField;
import com.extjs.gxt.ui.client.widget.form.ComboBox.TriggerAction;
import com.extjs.gxt.ui.client.widget.grid.CheckBoxSelectionModel;
import com.extjs.gxt.ui.client.widget.grid.ColumnConfig;
import com.extjs.gxt.ui.client.widget.grid.ColumnModel;
import com.extjs.gxt.ui.client.widget.grid.Grid;
import com.extjs.gxt.ui.client.widget.grid.GridSelectionModel;
import com.extjs.gxt.ui.client.widget.grid.filters.GridFilters;
import com.extjs.gxt.ui.client.widget.grid.filters.StringFilter;
import com.extjs.gxt.ui.client.widget.layout.BorderLayout;
import com.extjs.gxt.ui.client.widget.layout.BorderLayoutData;
import com.extjs.gxt.ui.client.widget.toolbar.PagingToolBar;
import com.extjs.gxt.ui.client.widget.toolbar.ToolBar;

public class SerieForm extends ContentPanel{

    Button addSerie;
	ToolBar toolBar;
	LayoutContainer cpc,cpw;
	BorderLayoutData sup,inf,east,center,filter,buttons,gridc;
	FormPanel fp,f;
	TextField<String> serie,descripcion,ultimonumero,longitudnumero,parametro,tipodocumento;
	TextField<String> serief,descripcionf,ultimonumerof,longitudnumerof,parametrof,tipodocumentof;
	HiddenField<String> id,tipodocumento_id;
	private FormBinding formbinding;
	ComboBox<BeanModel> cbtdf;
	String idtd;
	Dialog dl;
	
	public SerieForm(){
				
	/*	BorderLayout layout = new BorderLayout();
		setLayout(layout);
		addForm();	
		formulario();
	    cpw = new ContentPanel();
	  
	    sup = new BorderLayoutData(LayoutRegion.NORTH);
        inf = new BorderLayoutData(LayoutRegion.SOUTH);
	    cpw.add(fp,sup);
	    cpw.add(contPanel(),inf);
	     
	    east = new BorderLayoutData(LayoutRegion.EAST,350);
	    east.setSplit(true);
	    east.setCollapsible(true);
	    
	    center  = new BorderLayoutData(LayoutRegion.CENTER);
	    center.setCollapsible(true);
	    
	    ContentPanel ctp = new ContentPanel();
	    ctp.setLayout(new BorderLayout());
	    ctp.setHeading("Listado de Series");
	    ctp.setIconStyle("images/icons/table.png");
	    ctp.setHeaderVisible(false);
	    ctp.setCollapsible(true);
	    
	    filter  = new BorderLayoutData(LayoutRegion.NORTH,25);
	    gridc   = new BorderLayoutData(LayoutRegion.CENTER);
	    buttons = new BorderLayoutData(LayoutRegion.SOUTH,25);
	    
		Series.getPaginate();
		
        final PagingToolBar toolBarPag = new PagingToolBar(10);
        toolBarPag.bind(Series.loader);
        
        List<ColumnConfig> columns = new ArrayList<ColumnConfig>();
        
        final CheckBoxSelectionModel<BeanModel> sm = new CheckBoxSelectionModel<BeanModel>();       
        columns.add(sm.getColumn());
        columns.add(new ColumnConfig("serie", "Serie", 150));        
        columns.add(new ColumnConfig("descripcion", "Descripcion", 150));
        columns.add(new ColumnConfig("ultimonumero", "Ultimo Codigo", 150));
        columns.add(new ColumnConfig("longitudnumero", "Longitud Numero", 150));
        columns.add(new ColumnConfig("parametro", "Parametro", 150));
        columns.add(new ColumnConfig("tipodocumento", "Tipo Documento", 150));
        
        ColumnModel cm = new ColumnModel(columns);
        
        Grid<BeanModel> grid = new Grid<BeanModel>(Series.store, cm);  
        grid.addListener(Events.Attach, new Listener<GridEvent<BeanModel>>() {  
          public void handleEvent(GridEvent<BeanModel> be) {  
        	  Series.loader.load(0, 10);  
          }  
        }); 
        
        grid.setSelectionModel(sm);
        
//        GridSelectionModel<BeanModel> selector =new GridSelectionModel<BeanModel>();
//        selector.
//        
//       
        
        grid.getSelectionModel().addListener(Events.SelectionChange,
                new Listener<SelectionChangedEvent<BeanModel>>() {

				@Override
				public void handleEvent(SelectionChangedEvent<BeanModel> be) {		
					  if (be.getSelection().size() > 0) {
	            		  formbinding.bind((BeanModel) be.getSelection().get(0));  
		                } else {  
		                  formbinding.unbind();  
		                }
				}
        	
        });
        
        grid.setLoadMask(true);  
        grid.setBorders(true);               
       
        toolBar = new ToolBar(); 
        addSerie = new Button("Agregar", IconHelper.createPath("images/icons/new.gif"));
              
	
        
        GridFilters filters = new GridFilters();
        
        StringFilter serieFilter = new StringFilter("serie");        
        StringFilter descripcionFilter = new StringFilter("descripcion");
        StringFilter ultimonumeroFilter = new StringFilter("ultimonumero");
        StringFilter tipodocumentoFilter = new StringFilter("tipodocumento");
        
     
        filters.addFilter(serieFilter);        
        filters.addFilter(descripcionFilter);
        filters.addFilter(ultimonumeroFilter);
        filters.addFilter(tipodocumentoFilter);

        
        grid.addPlugin(filters);                
        grid.addPlugin(sm);
        
		setHeaderVisible(false);	
		formbinding = new FormBinding(fp, true); 
	    formbinding.addFieldBinding(new FieldBinding(id,"id"));
	    formbinding.addFieldBinding(new FieldBinding(serie,"serie"));
	    formbinding.addFieldBinding(new FieldBinding(descripcion,"descripcion"));
	    formbinding.addFieldBinding(new FieldBinding(ultimonumero,"ultimonumero"));
	    formbinding.addFieldBinding(new FieldBinding(longitudnumero,"longitudnumero"));
	    formbinding.addFieldBinding(new FieldBinding(parametro,"parametro"));
	    formbinding.addFieldBinding(new FieldBinding(tipodocumento,"tipodocumento"));
	    formbinding.addFieldBinding(new FieldBinding(tipodocumento_id,"tipodocumento_id"));
	    
	    ctp.add(bbutonbar(),filter);
	    ctp.add(grid,gridc);
	    ctp.add(toolBarPag,buttons);
	       
	    add(ctp,center);
	    add(cpw,east);
	}

	
	public ContentPanel contPanel(){
	   ContentPanel cp  = new ContentPanel();
	   return cp;
    }
	
	 public ButtonBar bbutonbar(){
		   dl = new Dialog();  
		   dl.setBodyBorder(false);  
		   dl.setHeading("Nuevo");  
		   dl.setWidth(330);  
		   dl.setHeight(300); 
		   
		  // ButtonBar btnbar = new ButtonBar();
		   Button salir  = new Button("Salir",IconHelper.create("images/icons/exit.png"));
		   Button guardar = new Button("Guardar",IconHelper.create("images/icons/save_all.png"));
		  
		   dl.setButtons("");
		   dl.addButton(salir);
		   dl.addButton(guardar);
			
		   dl.setFrame(true);

		   
		   salir.addSelectionListener(new SelectionListener<ButtonEvent>(){
			  public void componentSelected(ButtonEvent ce){
				  dl.hide();
				  clearForm();
			  }
		   });
		   guardar.addSelectionListener(new SelectionListener<ButtonEvent>(){
			   public void componentSelected(ButtonEvent ve){
				 System.out.println("el numero idtd"+idtd);  
				 if(idtd!=null){
                  Serie s = new Serie();
                   s.setSerie(serief.getValue());
                   s.setDescripcion(descripcionf.getValue());
                   s.setUltimonumero(ultimonumerof.getValue());
                   s.setLongitudnumero(Integer.parseInt(longitudnumerof.getValue()));
                   s.setParametro(parametrof.getValue());
                   s.setTipodocumento_id(Integer.parseInt(idtd));
                   Series.sf = SerieForm.this;
                   Series.guardar(s);
                   Series.loader.load();
				 }
      		   }
		   });
		 		 	  
		  ButtonBar bb = new ButtonBar();
		  Button btnNew = new Button("Nuevo",IconHelper.createPath("images/icons/new.gif"));
		  Button btnUpdate = new Button("Actualizar",IconHelper.createPath("images/icons/update.png"));
		  Button btnEliminar = new Button("Eliminar",IconHelper.createPath("images/icons/delete.gif"));
		  bb.add(btnNew);
		  bb.add(btnUpdate);
		  bb.add(btnEliminar);
		  
		  btnNew.addSelectionListener(new SelectionListener<ButtonEvent>() {
		      public void componentSelected(ButtonEvent ce) {
		          dl.add(f);
		          dl.show(); 
			      }
		    });
		  
		  btnUpdate.addSelectionListener(new SelectionListener<ButtonEvent>(){
			  public void componentSelected(ButtonEvent be){
                Serie sr = new Serie();
                 sr.setId(Integer.parseInt(id.getValue()));
                 sr.setSerie(serie.getValue());
                 sr.setDescripcion(descripcion.getValue());
                 sr.setUltimonumero(ultimonumero.getValue());
                 sr.setLongitudnumero(Integer.parseInt(longitudnumero.getValue()));
                 sr.setParametro(parametro.getValue());
                 sr.setTipodocumento_id(Integer.parseInt(tipodocumento_id.getValue()));
                Series.actualizar(sr);
                Series.loader.load();
			  }
		  });
		  
		  btnEliminar.addSelectionListener(new SelectionListener<ButtonEvent>(){
			 public void componentSelected(ButtonEvent ce){
				 if(id.getValue() != null){
					 Series.eliminar(Integer.parseInt(id.getValue()));
					 Series.loader.load();
				 }else{
					 MessageBox.alert("Seleccionar","Seleccione la fila porfavor", null);	 
				 }
			 }
		  });
		  
		  return bb;
	  }
	 
	 public void formulario(){
		f = new FormPanel();
		f.setHeaderVisible(false);
		f.setFrame(true);
	    serief = new TextField<String>();
		serief.setFieldLabel("Serie");
		descripcionf = new TextField<String>();
		descripcionf.setFieldLabel("Descripcion");
		ultimonumerof = new TextField<String>();
		ultimonumerof.setFieldLabel("Ultimo Codigo");
		longitudnumerof = new TextField<String>();
		longitudnumerof.setFieldLabel("Longitud Numero");
		parametrof = new TextField<String>();
		parametrof.setFieldLabel("Parametro");
		
		cbtdf = new ComboBox<BeanModel>();
		cbtdf.setEmptyText("Select a state...");  
		cbtdf.setDisplayField("descripcion");  
		cbtdf.setFieldLabel("Tipo Documento");
		cbtdf.setWidth(150);  
	    TipoDocumentos.getStore();
		cbtdf.setStore(TipoDocumentos.storeCombo);
		cbtdf.setValueField("descripcion");
		cbtdf.setTypeAhead(true);  
		cbtdf.setTriggerAction(TriggerAction.ALL);
		cbtdf.addSelectionChangedListener(new SelectionChangedListener<BeanModel>(){
		@Override
		public void selectionChanged(SelectionChangedEvent<BeanModel> se) {
			idtd = cbtdf.getValue().get("id").toString(); 
	        System.out.println("idtd"+idtd);   
	     }
		});	
		f.add(serief);
		f.add(descripcionf);
		f.add(ultimonumerof);
		f.add(longitudnumerof);
		f.add(parametrof);
		f.add(cbtdf);
			
	 }
	 
	 

		public void addForm(){
			fp = new FormPanel();
			id = new HiddenField<String>();
			id.setVisible(false);
		    serie = new TextField<String>();
			serie.setFieldLabel("Serie");
			descripcion = new TextField<String>();
			descripcion.setFieldLabel("Descripcion");
			ultimonumero = new TextField<String>();
			ultimonumero.setFieldLabel("Ultimo Codigo");
			parametro = new TextField<String>();
			parametro.setFieldLabel("Parametro");
			longitudnumero = new TextField<String>();
			longitudnumero.setFieldLabel("Longitud Numero");
			tipodocumento = new TextField<String>();
			tipodocumento.setFieldLabel("Tipo Documento");
			tipodocumento_id = new HiddenField<String>();
			tipodocumento_id.setVisible(false);
			fp.add(id);
			fp.add(serie);
			fp.add(descripcion);
	        fp.add(ultimonumero);
	        fp.add(parametro);
	        fp.add(longitudnumero);
	        fp.add(tipodocumento);
	        fp.add(tipodocumento_id);
	     }
		
		public void clearForm(){
			serief.clear();
			descripcionf.clear();
			ultimonumerof.clear();
			parametrof.clear();
			longitudnumerof.clear();*/
		}
}